package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Jt
 * @date 2021/4/23 19:21
 */
@Service
@Transactional
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 存储喜欢的数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry;
        if (user != null) {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),null);
        } else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEquipmentId());
        }
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"相关的行为实体不存在");
        }
//        查询对应的点赞行为是否存在
        ApLikesBehavior likesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
        if (likesBehavior == null) {
//            添加行为实体数据
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setType((short)0);
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setCreatedTime(new Date());
            save(likesBehavior);
        } else {
//            修改行为实体数据
            likesBehavior.setOperation(dto.getOperation());
            updateById(likesBehavior);
        }
        return ResponseResult.okResult();
    }
}
